package com.orangelife.service.outexcell;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemakerModel {
	private Configuration configuration = null;

	@SuppressWarnings("deprecation")
	public FreemakerModel() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");

	}

	public void create(Map<String, Object> dataMap, String savePath,
			String ftlName, FileOutputStream fileOutputStream) {
		configuration.setClassForTemplateLoading(this.getClass(), "ftl");
		Template t = null;
		try {
			t = configuration.getTemplate(ftlName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		File outFile = new File(savePath);
		Writer out = null;

		if (fileOutputStream != null) {
			try {
				out = new BufferedWriter(new OutputStreamWriter(
						fileOutputStream, "utf-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			try {
				out = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream(outFile), "utf-8"));
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		try {
			t.process(dataMap, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
